package com.jigang.study.netty.io.nio;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * NIO Time Server
 *
 * @author wujigang
 * @date 2019/8/15
 */
public class NioTimeServer {

    public static void main(String[] args) throws IOException {

        int port = 8080;

        MultiplexerTimeServer timeServer = new MultiplexerTimeServer(port);

        new Thread(timeServer, "NIO-MultiplexerTimeServer-001").start();
    }

    /**
     * 支持多个客户端接入的多路复用类
     */
    static class MultiplexerTimeServer implements Runnable {

        private Selector selector;

        private ServerSocketChannel serverSocketChannel;

        private AtomicBoolean running = new AtomicBoolean(false);

        public MultiplexerTimeServer(int port) {
            try {
                // 初始化多路复用器Selector
                selector = Selector.open();

                // 打开ServerSocketChannel，绑定端扣，并设置为非阻塞模式
                serverSocketChannel = ServerSocketChannel.open();
                serverSocketChannel.configureBlocking(false);
                serverSocketChannel.socket().bind(new InetSocketAddress(port), 1024);

                serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
                System.out.println("The time server is start in port: " + port);

            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
        }

        public void stop() {
            this.running.set(false);
        }

        @Override
        public void run() {

            running.compareAndSet(false, true);

            while (running.get()) {
                try {
                    selector.select(1000);
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();

                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();

                        try {
                            handleInput(key);
                        } catch (Exception e) {
                            if (null != key) {
                                key.cancel();
                                if (null != key.channel()) {
                                    key.channel().close();
                                }
                            }
                        }
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }

                // 多路复用器关闭后，所有注册在上面的Channel和Pipe等资源都会被自动去注册并关闭，所以不需要重复释放资源
                if (null != selector) {
                    try {
                        selector.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        /**
         * 处理输入
         *
         * @param key
         */
        private void handleInput(SelectionKey key) throws IOException {
            if (key.isValid()) {
                // 处理接入的请求消息
                if (key.isAcceptable()) {
                    ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    sc.register(selector, SelectionKey.OP_READ);
                }

                // 读取数据
                if (key.isReadable()) {
                    SocketChannel sc = (SocketChannel) key.channel();

                    ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                    int readBytes = sc.read(readBuffer);

                    if (readBytes > 0) {
                        readBuffer.flip();
                        byte[] bytes = new byte[readBuffer.remaining()];
                        readBuffer.get(bytes);

                        String body = new String(bytes, "UTF-8");
                        System.out.println("The time server receive order : " + body);

                        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date().toString() : "BAD ORDER";

                        doWrite(sc, currentTime);
                    } else if (readBytes < 0) {
                        key.cancel();
                        sc.close();
                    } else {
                        // 读取到0字节，忽略
                    }
                }
            }
        }

        /**
         * 写数据
         *
         * @param channel
         * @param response
         * @throws IOException
         */
        private void doWrite(SocketChannel channel, String response) throws IOException {

            if (response != null && response.trim().length() > 0) {
                byte[] bytes = response.getBytes();

                ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
                writeBuffer.put(bytes);
                writeBuffer.flip();
                channel.write(writeBuffer);
            }
        }
    }
}
